<?php

namespace App\Models;

use App\Util\Url;
use Illuminate\Database\Eloquent\Model;

class MyCourse extends Model
{
    protected $table = "c_my_course";

    public function course()
    {
        return $this->belongsTo('App\Models\Course', 'course_id');
    }

    public function works()
    {
        return $this->belongsTo('App\Models\DoctorWorks', 'work_id');
    }


    /**
     * @param $data
     * 获取我的课程未读
     */
    public function getMineNoReadCourse($data)
    {
        return self::where([['user_id','=',$data['user_id']],['is_read','=',1]])->count();
    }



    /**
     * @param $uid
     * @return array
     * 我的课程列表（用户端
     */
    public function getMyCourseList($uid)
    {
        $res = self::where([['user_id', '=', $uid]])->with(['course', 'works'])->orderByDesc("id")->simplePaginate();
        if ($res->isEmpty()) {
            return [];
        }
        $lit =  $res->toArray();
        $host = new Url();
        foreach ($lit['data'] as $k => &$v) {
            if($v['course']){
                $v['course']['course_img'] = $host::getHttpHost() . 'upload/' . $v['course']['course_img'];
            }
            else{
               self::where([['course_id','=',$v['course_id']],['user_id','=',$v['user_id']]])->delete();
               continue;
            }
        }
        return $lit;
    }


    /***
     * @param $filter
     * 添加我的课程
     */
    public function addMyCourse($filter)
    {
        $info = (new Course())->where([['id','=',$filter['course_id']]])->first();
        if($info->course_price  > 0 ){
            return 0;
        }
        $isAdd = self::where([['course_id','=',$filter['course_id']],['work_id','=',$filter['work_id']],['user_id','=',$filter['user_id']]])->first();
        if($isAdd){
            return 0;
        }
        $this->course_id = $filter['course_id'];
        $this->work_id = $filter['work_id'];
        $this->user_id = $filter['user_id'];
        return $this->save();
    }
    
}
